<!-- 合同-基础设置-合同类型及模板-新增分组 -->
<template>
  <a-modal
    width="40%"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    draggable
    title-align="center"
    unmountOnClose
  >
    <template #title>
      {{ props.data?.id ? '编辑分组' : '新增分组' }}
    </template>
    <div>
      <a-form
        :model="formData.data"
        ref="refForm"
        :rules="rules"
        auto-label-width
      >
        <a-form-item label="分组名称" field="name" show-colon>
          <a-input v-model="formData.data.name" style="width: 250px"></a-input>
        </a-form-item>
        <a-form-item label="分组类型" field="type" show-colon>
          <a-radio-group v-model="formData.data.type">
            <a-radio :value="1">合同</a-radio>
            <a-radio :value="2">协议</a-radio>
            <a-radio :value="3">企业公文</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="分组描述" field="remark" show-colon>
          <a-textarea
            v-model="formData.data.remark"
            show-word-limit
            :max-length="50"
            :auto-size="{
              minRows: 4
            }"
          ></a-textarea>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { cloneDeep } from 'lodash';
import { CheckContractGroup } from '@/apis/management/contract/baseSetting';
const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    data?: any; // 传进来的数据,
  }>(),
  {}
);

const emits = defineEmits(['update:visible', 'groupEmit']);
let refForm = ref();

const formData = reactive<any>({
  data: {
    name: '', // 合同类型名称
    type: 1,
    remark: '' // 备注
  }
});

const validateName = async (name: string, cb: any) => {
  try {
    if (name === props.data?.name && props.data?.id) {
      //
    } else {
      const data = {
        name
      };
      const res = await CheckContractGroup(data);
      if (res?.code) {
        cb(res.msg);
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

const rules = {
  name: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateName
    }
  ],
  type: [
    {
      required: true,
      message: '请选择'
    }
  ]
};

watch(
  () => props.visible,
  (newVal: boolean) => {
    if (newVal) {
      if (props.data) formData.data = cloneDeep(props.data);
      else
        formData.data = {
          name: '', // 合同类型名称
          type: 1,
          remark: '' // 备注
        };
      //
    }
  }
);

const handleOk = async () => {
  if (await refForm.value.validate()) {
    return;
  }
  emits('groupEmit', formData.data);
  emits('update:visible', false);
};

const handleCancel = () => {
  emits('update:visible', false);
};
</script>

<style scoped lang="less"></style>
